
import { apiConf } from '@/config';
import auth from '@/service/auth';
import urls from './url-type';
import urlUtils from '../libs/urlutils';

/**
 * 填充 baseUrl
 *
 * @param {any} url
 * @param {any} baseUrl
 * @returns
 */
function fillBaseUrl(url, baseUrl) {
  if (url.indexOf('//') > -1) {
    return url;
  }
  baseUrl = baseUrl || apiConf.baseUrl;

  return `${baseUrl}${url}`;
}

/**
 * 组装http请求
 * @param  {Object, String} urlVal [description]
 * @return {function(*=): void}        [description]
 */
function assembleHttp(urlVal) {
  if (typeof urlVal === 'string') {
    urlVal = {
      url: urlVal,
      method: 'post',
      baseUrl: apiConf.baseUrl,
    };
  }

  urlVal.url = fillBaseUrl(urlVal.url, urlVal.baseUrl);

  return (params = {}) => {
    // const token = auth.getToken();
    // const language = auth.getLang();
    params.token = auth.getToken();
    params.language = auth.getLang();
    const url = urlUtils.fillParams(params, urlVal.url, []);
    // console.log(url);
    window.open(url);
  };
}

/**
 * 填充方法
 * @param  {Object} apiObj [description]
 * @param  {Object} urls   [description]
 * @return {[type]}        [description]
 */
function fillMethods(apiObj, urls) {
  const urlKeys = Object.keys(urls);

  urlKeys.forEach((urlKey) => {
    const urlVal = urls[urlKey];

    if (typeof urlVal === 'string') {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else if (urlVal.url) {
      apiObj[urlKey] = assembleHttp(urlVal);
    } else {
      apiObj[urlKey] = {};
      fillMethods(apiObj[urlKey], urlVal);
    }
  });
}

/**
 * ExportExcel 类
 */
class ExportExcel {
  /**
   * 作为Vue插件进行安装，挂载到Vue.prototype
   */
  install(Vue) {
    // eslint-disable-next-line
    Vue.prototype.$exportExcel = this;
  }
}

fillMethods(ExportExcel.prototype, urls);


export default new ExportExcel();
